import { useEffect, useRef, useState } from "react"
//通过点击验证码实现倒计时，实现封装hooks，刷新页面倒计时不重新开始
function useCountDown(num = 30) {
    const [count, setCount] = useState(num)
    const [isRun, setIsRun] = useState(false)

    const ref = useRef(null)

    const startFn = () => {
        setIsRun(true);
        ref.current = setInterval(() => {
            setCount((count) => {

                const nCount = count - 1
                
                if(nCount <= 0) {
                    clearInterval(ref.current)
                    setIsRun(false);
                    setCount(num)
                }

                return nCount
            })
        }, 1000);
    }

    useEffect(() => {
        return () => {

            clearInterval(ref.current)
        }
    }, [])

    return { count, startFn, isRun }
}

export default useCountDown
